package com.alliky.core.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alliky.core.R;
import com.alliky.core.net.ImageLoader;
import com.alliky.core.utils.CollectionUtils;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: wxianing
 * @CreateDate: 2022/8/6 11:49
 * @Description: java类作用描述
 */
public class ViewAlbumLayout extends LinearLayout {

    private int maxChooseCount = 9;
    private boolean editable = true;
    private AlbumAdapter mAdapter;

    private TextView tvCount;
    private TextView tvAlbumHint;
    private View rootView;
    private FragmentActivity mActivity;

    public ViewAlbumLayout(Context context) {
        super(context);
        mActivity = (FragmentActivity) context;
        init(context, null);
    }

    public ViewAlbumLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mActivity = (FragmentActivity) context;
        init(context, attrs);
    }

    public ViewAlbumLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mActivity = (FragmentActivity) context;
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        View convertView = LayoutInflater.from(context).inflate(R.layout.view_album_choose_layout, this, true);
        View convertFoot = LayoutInflater.from(context).inflate(R.layout.view_album_empty_layout, null, false);

        RecyclerView recyclerView = convertView.findViewById(R.id.recyclerView);
        tvAlbumHint = convertView.findViewById(R.id.tvAlbumHint);
        tvCount = convertView.findViewById(R.id.tvCount);
        rootView = convertView.findViewById(R.id.rootView);

//        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setLayoutManager(new GridLayoutManager(context, 4));

        List<String> images = new ArrayList<>();
        images.add("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2Ftp09%2F210F2130512J47-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1662382950&t=94c3a7d23bbdc18487a8d54e8b08481c");
        images.add("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.daimg.com%2Fuploads%2Fallimg%2F210103%2F1-210103211Z8.jpg&refer=http%3A%2F%2Fimg.daimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1662382950&t=41b927d942e0a677f8d9143eccd48120");
        mAdapter = new AlbumAdapter(images);

        mAdapter.addFooterView(convertFoot);
        recyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.iv_thumb) {
                //todo 点击放大图片

            } else if (view.getId() == R.id.iv_delete) {
                mAdapter.remove(position);
                updateFoot();
            }
        });
        convertFoot.setOnClickListener(v -> {
            addThumb();
        });
    }

    private void addThumb() {
        if (mAdapter.getData().size() >= maxChooseCount) {
            RxToast.error("最多可以上传" + maxChooseCount + "张图片");
            return;
        }

        PictureSelector.create(mActivity)
                .openCamera(PictureMimeType.ofImage())// 单独拍照，也可录像或也可音频 看你传入的类型是图片or视频
                .theme(R.style.picture_default_style)
                .compress(true) //是否压缩
//                            .maxSelectNum(maxSelectNum)// 最大图片选择数量
//                            .isUseCustomCamera(cb_custom_camera.isChecked())// 是否使用自定义相机
                //.setOutputCameraPath()// 自定义相机输出目录，只针对Android Q以下，例如 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) +  File.separator + "Camera" + File.separator;
                .minSelectNum(1)// 最小选择数量
//                .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                .enableCrop(false)// 是否裁剪
                //.querySpecifiedFormatSuffix(PictureMimeType.ofPNG())// 查询指定后缀格式资源
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                //.cameraFileName(System.currentTimeMillis() + ".jpg")// 使用相机时保存至本地的文件名称,注意这个只在拍照时可以使用
                //.renameCompressFile(System.currentTimeMillis() + ".jpg")// 重命名压缩文件名、 注意这个不要重复，只适用于单张图压缩使用
                //.renameCropFileName(System.currentTimeMillis() + ".jpg")// 重命名裁剪文件名、 注意这个不要重复，只适用于单张图裁剪使用
                //.basicUCropConfig()//对外提供所有UCropOptions参数配制，但如果PictureSelector原本支持设置的还是会使用原有的设置
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                            .withAspectRatio(aspect_ratio_x, aspect_ratio_y)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
//                            .circleDimmedLayer(cb_crop_circular.isChecked())// 是否圆形裁剪
                //.setCircleDimmedColor(ContextCompat.getColor(this, R.color.app_color_white))// 设置圆形裁剪背景色值
                //.setCircleDimmedBorderColor(ContextCompat.getColor(this, R.color.app_color_white))// 设置圆形裁剪边框色值
                //.setCircleStrokeWidth(3)// 设置圆形裁剪边框粗细
                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                //.cropCompressQuality(90)// 废弃 改用cutOutQuality()
                .minimumCompressSize(100)// 小于100kb的图片不压缩
//                            .cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                //.cropImageWideHigh()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                //.rotateEnabled() // 裁剪是否可旋转图片
                //.scaleEnabled()// 裁剪是否可放大缩小图片
                //.videoQuality()// 视频录制质量 0 or 1
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        if (!CollectionUtils.isEmpty(result)) {
                            List<String> list = new ArrayList<>();
                            for (LocalMedia media : result) {
                                if (media.isCut()) {
                                    list.add(media.getCutPath());
                                } else {
                                    if (media.isCompressed()) {
                                        list.add(media.getCompressPath());
                                    } else {
                                        list.add(media.getPath());
                                    }
                                }
                            }
                            mAdapter.addData(list);
                        }
                    }

                    @Override
                    public void onCancel() {

                    }
                });//结果回调onActivityResult code
    }

    public void setAlbumLyaoutVisiable(boolean boo) {
        if (boo) {
            rootView.setVisibility(VISIBLE);
        } else {
            rootView.setVisibility(GONE);
        }
    }

    private void updateFoot() {
        if (!editable) {
            mAdapter.getFooterLayout().setVisibility(GONE);
            return;
        }
        if (mAdapter.getData().size() >= maxChooseCount) {
            mAdapter.getFooterLayout().setVisibility(GONE);
        } else {
            mAdapter.getFooterLayout().setVisibility(VISIBLE);
        }
        tvCount.setText("(" + mAdapter.getData().size() + "/" + maxChooseCount + ")");
    }

    public void disableEdit() {
        editable = false;
        updateFoot();
        tvAlbumHint.setEnabled(false);
        tvAlbumHint.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
    }

    public void bind(List<String> data) {
        mAdapter.setNewData(data);
        updateFoot();
    }

    class AlbumAdapter extends BaseQuickAdapter<String, BaseViewHolder> {

        public AlbumAdapter(@org.jetbrains.annotations.Nullable List<String> data) {
            super(R.layout.item_ablum_layout, data);
        }

        @Override
        protected void convert(@NotNull BaseViewHolder holder, String item) {
            holder.addOnClickListener(R.id.iv_thumb, R.id.iv_delete);


            ImageLoader.load( item, holder.getView(R.id.iv_thumb));

            if (editable) {
                holder.setGone(R.id.iv_delete, true);
            } else {
                holder.setGone(R.id.iv_delete, false);
            }
        }
    }
}
